import { ref, Ref } from 'vue'
import { SpsFormProps } from '../Form'
import { bindMethod } from '../../../utils'
import { FormEvents } from '../types'

export default function useToolButton(model: Ref<any>, emit: Function) {
  const formRef: Ref<any> = ref(null)
  const resetHandler = (model: Ref<any>, formRef: Ref<any>) => {
    model.value = {}
    formRef.value.resetFields()
    emit('reset')
  }
  const submitHandler = async (model: Ref<any>, formRef: Ref<any>) => {
    try {
      await formRef.value.validate()
      emit('submit', model.value)
    } catch {}
  }
  bindMethod('reset', () => resetHandler(model, formRef))
  bindMethod('submit', () => submitHandler(model, formRef))
  const defaultEvents: FormEvents = {
    reset: {
      title: '重置',
      handler: resetHandler
    },
    submit: {
      title: '提交',
      type: 'primary',
      handler: submitHandler
    }
  }
  const renderToolButton = (props: SpsFormProps) => {
    const { actions, formEvents } = props
    const events = {
      ...defaultEvents,
      ...formEvents
    }
    return actions!.split(',').map((action) => {
      const event = events[action]
      if (!event) return null
      return (
        <a-button
          type={event.type}
          onClick={() => event.handler(model, formRef)}>
          {event.title}
        </a-button>
      )
    })
  }
  return {
    formRef,
    renderToolButton
  }
}
